unit uSecureApp;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, inifiles, OnGuard, OgUtil;

type
  TSecureApp = class(TForm)
    OgUsageCode1: TOgUsageCode;
    procedure FormCreate(Sender: TObject);
    procedure OgUsageCode1Checked(Sender: TObject; Status: TCodeStatus);
    procedure OgUsageCode1GetCode(Sender: TObject; var Code: TCode);
    procedure OgUsageCode1ChangeCode(Sender: TObject; Code: TCode);
    procedure OgUsageCode1GetKey(Sender: TObject; var Key: TKey);
  private
    CheckedTimes: integer;
    { Private declarations }
  public
    { Public declarations }
  end;

var
  SecureApp: TSecureApp;

implementation

{$R *.dfm}

procedure TSecureApp.FormCreate(Sender: TObject);
begin
  CheckedTimes := 0;
  OgUsageCode1.CheckCode(TRUE);
end;

procedure TSecureApp.OgUsageCode1ChangeCode(Sender: TObject; Code: TCode);
var
  IniFile: Tinifile;
  s: string;
begin
  IniFile := Tinifile.Create('usgprj1.ini');
  try
    s := BufferToHex(Code, sizeof(Code));
    IniFile.WriteString('Codes', 'UsageCode', s);
  finally
    IniFile.Free;
  end;
end;

procedure TSecureApp.OgUsageCode1Checked(Sender: TObject; Status: TCodeStatus);
var
  Code: TCode;
  IniFile: Tinifile;
  s: string;
begin
  // ShowMessage('runs reamining: ' + inttostr(OgUsageCode1.GetValue()));
  case Status of
    ogInvalidCode:
      begin
        inc(CheckedTimes);
        if InputQuery('Enter code number', 'Code', s) then
        begin
          if (HexToBuffer(s, Code, sizeof(Code))) then
          begin
            IniFile := Tinifile.Create('usgprj1.ini');
            IniFile.WriteString('Codes', 'UsageCode', s);
            IniFile.Free;
            OgUsageCode1.CheckCode(TRUE);
            exit;
          end;
        end;
      end;
    ogCodeExpired:
      begin
        ShowMessage('Code expired');
        ModalResult := mrClose;
      end;
    ogRunCountUsed:
      begin
        ShowMessage('Runs count exceeded');
        if CheckedTimes < 2 then
        begin
          OgUsageCode1Checked(self, ogInvalidCode);
        end;
        ModalResult := mrClose;
      end;
  end;
  if Status <> ogValidCode then
  begin
    application.Terminate;
  end
  else
  begin
    close();
  end;
end;

procedure TSecureApp.OgUsageCode1GetCode(Sender: TObject; var Code: TCode);
var
  IniFile: Tinifile;
  s: string;
begin
  IniFile := Tinifile.Create('usgprj1.ini');
  try
    s := IniFile.ReadString('Codes', 'UsageCode', '');
    HexToBuffer(s, Code, sizeof(Code));
  finally
    IniFile.Free;
  end;
end;

procedure TSecureApp.OgUsageCode1GetKey(Sender: TObject; var Key: TKey);
CONST
  CKey: TKey = ($D3, $7B, $D9, $1D, $2F, $1A, $20, $C9, $B1, $0D, $42, $01, $F3, $06, $DA, $72);
begin
  Key := CKey;
end;

end.
